import { Model } from "../../model";
import { RenderCommandSystem } from "../RenderCommandSystem";
import { ICommand } from "./ICommand";

/**
 * 渲染函数回调+模型场景批+渐进式的算法
 */
export class ModelCommand implements ICommand {
    nextStartIndex = 0;
    constructor(private rcs: RenderCommandSystem) {

    }
    reset(): ICommand {
        this.nextStartIndex = 0;
        window.performance.clearMarks();
        window.performance.clearMeasures();
        return this;
    }
    execute(): boolean {
        // console.log("nextStartIndex= ", this.nextStartIndex);
        window.performance.mark(`r-${this.nextStartIndex - 1}`);
        const model = this.rcs.getParam("model");
        const scenes = model.getScenes();
        const renderObjectCB = this.rcs.getParam("renderCb");
        let timeRemaining = this.rcs.frameBudget;

        // 优化成while会不会快一点？
        for (let index = this.nextStartIndex; index < scenes.length; index++) {

            renderObjectCB(scenes[index]);

            window.performance.mark(`r-${index}`);
            const duration = window.performance.measure("渲染一批的时长", `r-${index - 1}`, `r-${index}`).duration;
            // console.log("timeRemaining= ", timeRemaining, " duration= ", duration);
            timeRemaining -= duration;

            // 时间到了，没做完。
            // 但是本批次已经渲染，所以现场保护那里有个 + 1
            if (timeRemaining <= 0 && index < scenes.length - 1) {
                // 现场保护
                this.nextStartIndex = index + 1;
                return true; // 被中断
            }
            // 做完了
            if (index === scenes.length - 1) {
                this.nextStartIndex = 0;
                window.performance.clearMarks();
                window.performance.clearMeasures();
            }
        }

        return false; // 没有被中断
    }

}
